/*
 * @Author: wangdazhuang
 * @Date: 2025-01-13 14:52:40
 * @LastEditTime: 2025-02-20 14:43:52
 * @LastEditors: wangdazhuang
 * @Description: 
 * @FilePath: /pornhub_app/lib/views/player/views/media_kit_custom_controls.dart
 */

import 'dart:async';
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:media_kit_video/media_kit_video_controls/src/controls/methods/video_state.dart';
import 'package:media_kit_video/media_kit_video_controls/src/controls/widgets/video_controls_theme_data_injector.dart';
import 'package:pornhub_app/components/easy_toast.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/extension.dart';

import 'av_player_loading.dart';

// ignore: must_be_immutable
class MediaKitCustomControls extends StatefulWidget {
  final BuildContext buildContext;
  Size? viewSize;
  Rect? texturePos;
  BuildContext? pageContent;
  String? playerTitle;
  bool? hideBack;
  bool? hideFullScreen;

  MediaKitCustomControls({
    super.key,
    required this.buildContext,
    this.viewSize,
    this.texturePos,
    this.pageContent,
    this.playerTitle,
    this.hideBack = false,
    this.hideFullScreen = false,
  });

  @override
  // ignore: library_private_types_in_public_api
  _MediaKitCustomControlsState createState() => _MediaKitCustomControlsState();
}

class _MediaKitCustomControlsState extends State<MediaKitCustomControls> {
  // Player get player => controller(context).player;
  Duration _durationPos = const Duration(seconds: 0);
  Duration _currentPos = const Duration(seconds: 0);
  Duration _bufferPos = const Duration(seconds: 0);

  bool _playing = false;
  String _exception = '';

  double startPosX = 0;
  double startPosY = 0;
  Size playerBoxSize = Size.zero;

  double _seekPos = -1.0;

  StreamSubscription<Duration>? _currentPosSubs;

  StreamSubscription? _bufferPosSubs;

  StreamSubscription? _bufferingStateSubs;
  StreamSubscription? _erroreSubs;
  StreamSubscription<Duration>? _durationSubs;
  StreamSubscription<bool>? _playingSubs;

  bool _isBuffering = false;
  bool _showSpeed = false;
  String _speed = '1';
  final List<String> _speeds = ['0.5', '0.75', '1', '1.5', '2'];
  Timer? _hideTimer;
  bool _hideStuff = true;

  final barHeight = 55.0;
  final barContainerHeight = 35.0;

  final centerSeekBarHeight = 5.0;

  final centerBtnSize = 45.0;
  final thumbSize = 18.0;

  bool tapped = false;
  double slider = 0.0;

  ///简单的时间转换方法
  String _duration2String(Duration duration) {
    if (duration.inMilliseconds < 0) {
      return "-: negtive value and ilegal value!";
    }
    String twoDigits(int n) {
      if (n >= 10) return "$n";
      return "0$n";
    }

    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    int inHours = duration.inHours;
    return inHours > 0
        ? "$inHours:$twoDigitMinutes:$twoDigitSeconds"
        : "$twoDigitMinutes:$twoDigitSeconds";
  }

  @override
  void didChangeDependencies() {
    _addSubscriptionListeners();
    super.didChangeDependencies();
  }

  ///监听器
  void _addSubscriptionListeners() {
    Player player = controller(context).player;

    // ///是否正在播放
    // _playingSubs = player.stream.playing.listen((v) {
    //   if (mounted) {
    //     setState(() {
    //       _playing = v;
    //     });
    //   }
    // });

    // ///当前进度
    _currentPosSubs = player.stream.position.listen((v) {
      if (mounted) {
        setState(() {
          _currentPos = v;
        });
      }
    });

    ///错误
    // _erroreSubs = player.stream.error.listen((e) {
    //   if (mounted) {
    //     setState(() {
    //       _exception = e;
    //     });
    //   }
    // });

    ///缓冲
    // _bufferPosSubs = player.stream.buffer.listen((v) {
    //   setState(() {
    //     _bufferPos = v;
    //   });
    // });

    ///时长
    // _durationSubs = player.stream.duration.listen((v) {
    //   setState(() {
    //     _durationPos = v;
    //   });
    // });

    ///是否正在缓冲
    _bufferingStateSubs = player.stream.buffering.listen((v) {
      if (mounted) {
        setState(() {
          _isBuffering = v;
        });
      }
    });
  }

  @override
  void dispose() {
    _hideTimer?.cancel();
    _currentPosSubs?.cancel();
    _durationSubs?.cancel();
    _bufferPosSubs?.cancel();
    _bufferingStateSubs?.cancel();
    _erroreSubs?.cancel();
    _playingSubs?.cancel();

    super.dispose();
  }

  void _startHideTimer() {
    _hideTimer?.cancel();
    _hideTimer = Timer(const Duration(seconds: 3), () {
      setState(() {
        _hideStuff = true;
      });
    });
  }

  void _cancelAndRestartTimer() {
    if (_hideStuff == true) {
      _startHideTimer();
    }
    setState(() {
      _hideStuff = !_hideStuff;
    });
  }

  // 底部左下按钮
  Widget _buildPlayStateBtn() {
    // IconData iconData = _playing ? Icons.pause : Icons.play_arrow;

    // return IconButton(
    //   icon: Icon(iconData),
    //   color: Colors.white,
    //   padding: const EdgeInsets.only(
    //     left: 10.0,
    //   ),
    //   splashColor: Colors.transparent,
    //   highlightColor: Colors.transparent,
    //   onPressed: _playOrPause,
    // );
    return const Padding(
      padding: EdgeInsets.only(left: 5),
      child: MaterialPlayOrPauseButton(
        iconColor: Colors.white,
        iconSize: 22,
      ),
    );
  }

  ///当前位置
  Widget _buildCurrentTime() {
    // return Padding(
    //   padding: const EdgeInsets.only(right: 5.0, left: 5),
    //   child: Text(
    //     _duration2String(_currentPos),
    //     style: const TextStyle(
    //       fontSize: 14.0,
    //       color: Colors.white,
    //     ),
    //   ),
    // );
    return const MaterialPositionIndicator(
      style: TextStyle(
        fontSize: 14.0,
        color: Colors.white,
      ),
    );
  }

  ///进度条
  Widget _buildSliderBar(BuildContext context) {
    final bottomH = isFullscreen(context)
        ? kIsWeb && Get.width < Get.height
            ? 25.0
            : 15.0
        : 27.0;
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.only(right: 5, left: 5),
        child: Padding(
          padding: EdgeInsets.only(bottom: bottomH),
          child: const MaterialSeekBar(),
        ),
      ),
    );
  }

  ///总时长
  // _buildDuration() {
  //   // logger.d('duration >>>>>>${_duration.inSeconds}');
  //   return Padding(
  //     padding: const EdgeInsets.only(right: 5.0, left: 5),
  //     child: Text(
  //       _duration2String(_durationPos),
  //       style: const TextStyle(
  //         fontSize: 14.0,
  //         color: Colors.white,
  //       ),
  //     ),
  //   );
  // }

  ///全屏按钮
  // _buildFullScreenBtn() {
  //   return IconButton(
  //     icon: const Icon(Icons.fullscreen),
  //     padding: const EdgeInsets.only(left: 5.0, right: 10.0),
  //     color: Colors.white,
  //     splashColor: Colors.transparent,
  //     highlightColor: Colors.transparent,
  //     onPressed: () {
  //       // final context = Get.context!;
  //       // if (isFullscreen(context)) {
  //       //   exitFullscreen(context);
  //       // } else {
  //       //   enterFullscreen(context);
  //       // }
  //     },
  //   );
  // }

  //倍速
  Widget _buildSpeedText() {
    final player = controller(context).player;
    return Text(
      '${_speed}X',
      style: const TextStyle(color: Colors.white),
    ).onTap(() {
      setState(() {
        _showSpeed = !_showSpeed;
      });
    });
  }

  // 底部
  AnimatedOpacity _buildBottomBar(BuildContext context) {
    final isInner = (widget.viewSize?.height ?? 0) < Get.height;
    final bottomH = isInner ? 0.0 : MediaQuery.of(context).padding.bottom;
    return AnimatedOpacity(
      opacity: _hideStuff ? 0.0 : 0.8,
      duration: const Duration(milliseconds: 400),
      child: Container(
        height: barHeight,
        padding: EdgeInsets.only(bottom: bottomH),
        alignment: Alignment.center,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topRight,
            colors: [
              Color.fromRGBO(0, 0, 0, 0),
              Color.fromRGBO(0, 0, 0, 0.7),
            ],
          ),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            // 按钮 - 播放/暂停
            _buildPlayStateBtn(),
            // 已播放时间
            _buildCurrentTime(),
            // 播放进度
            _buildSliderBar(context),
            // 总播放时间
            // _buildDuration(),
            // 倍速
            const SizedBox(
              width: 10,
            ),
            _buildSpeedText(),
            // 按钮 - 全屏/退出全屏
            // _buildFullScreenBtn(),
            widget.hideFullScreen == true
                ? const SizedBox(width: 10)
                : const MaterialFullscreenButton()
          ],
        ),
      ),
    );
  }

  // 播放器顶部 返回 + 标题
  AnimatedOpacity _buildTopBar(BuildContext context) {
    final isFull = widget.viewSize?.height == Get.height;
    final fullButtonTop = MediaQuery.of(widget.buildContext).padding.top;
    final opac = isFull
        ? _hideStuff
            ? 0.0
            : 1.0
        : 1.0;
    // const decoration = BoxDecoration(
    //   gradient: LinearGradient(
    //     begin: Alignment.topRight,
    //     colors: [
    //       Color.fromRGBO(0, 0, 0, 0.7),
    //       Color.fromRGBO(0, 0, 0, 0),
    //     ],
    //   ),
    // );
    final back = IconButton(
      icon: const Icon(
        Icons.arrow_back_ios,
        size: 25,
        color: COLOR.white,
      ),
      color: Colors.white,
      padding: const EdgeInsets.only(left: 10.0, right: 10.0),
      splashColor: Colors.transparent,
      highlightColor: Colors.transparent,
      onPressed: () {
        if (isFullscreen(context)) {
          exitFullscreen(context);
        } else {
          Get.back();
        }
      },
    );
    return AnimatedOpacity(
      opacity: 1.0,
      duration: const Duration(milliseconds: 400),
      child: Container(
        margin: EdgeInsets.only(top: isFull ? fullButtonTop : 15),
        height: 44.0,
        alignment: Alignment.centerLeft,
        child: isFullscreen(context)
            ? back
            : widget.hideBack == true
                ? const SizedBox.shrink()
                : back,
      ),
    );
  }

// 暂停 + 播放
  _buildPlayPauseBtn() {
    // return EasyButton.child(
    //     width: centerBtnSize,
    //     height: centerBtnSize,
    //     Icon(_playing ? Icons.pause : Icons.play_arrow,
    //         size: centerBtnSize, color: Colors.white),
    //     onTap: _playOrPause);
    return MaterialPlayOrPauseButton(
        iconSize: centerBtnSize, iconColor: Colors.white);
  }

  ///快退快进
  _forwardOrBackAction(bool back, BuildContext _) async {
    final player = controller(_).player;
    var current = _currentPos.inSeconds;
    if (back) {
      ///快退
      current = current - 10;
      if (current < 0) current = 0;
      await player.seek(Duration(seconds: current));
    } else {
      ///快进
      current = current + 10;
      if (current > _durationPos.inSeconds && _durationPos != Duration.zero) {
        current = _durationPos.inSeconds;
      }
      await player.seek(Duration(seconds: current));
    }
  }

//快退
  _buildBack10Btn(BuildContext _) {
    // return EasyButton.child(
    // Icon(
    //   Icons.replay_10_outlined,
    //   color: Colors.white,
    //   size: centerBtnSize,
    // ),
    //     width: centerBtnSize,
    //     height: centerBtnSize,
    //     onTap: () => _forwardOrBackAction(true));
    return MaterialCustomButton(
      onPressed: () => _forwardOrBackAction(true, _),
      icon: Icon(
        Icons.replay_10_outlined,
        color: Colors.white,
        size: centerBtnSize,
      ),
      iconSize: centerBtnSize,
    );
  }

  ///快进
  _buildForward10Btn(BuildContext _) {
    // return EasyButton.child(
    //     Icon(
    //       Icons.forward_10_outlined,
    //       color: Colors.white,
    //       size: centerBtnSize,
    //     ),
    //     width: centerBtnSize,
    //     height: centerBtnSize,
    //     onTap: () => _forwardOrBackAction(false));
    return MaterialCustomButton(
      onPressed: () => _forwardOrBackAction(false, _),
      icon: Icon(
        Icons.forward_10_outlined,
        color: Colors.white,
        size: centerBtnSize,
      ),
      iconSize: centerBtnSize,
    );
  }

  // 居中按钮
  Widget _buildCenterBtns(BuildContext _) {
    return Container(
      color: Colors.transparent,
      height: double.infinity,
      width: double.infinity,
      child: Center(
        child: _currentPos.inMilliseconds > 0
            ? AnimatedOpacity(
                opacity: _hideStuff ? 0.0 : 0.7,
                duration: const Duration(milliseconds: 400),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    _buildBack10Btn(_),
                    const SizedBox(width: 20),
                    _buildPlayPauseBtn(),
                    const SizedBox(width: 20),
                    _buildForward10Btn(_),
                  ],
                ),
              )
            : const AvPlayerLoading(),
      ),
    );
  }

  ///中间
  _buildCenterBox(BuildContext context) {
    // 中间按钮
    return Expanded(
      child: GestureDetector(
        onTap: () {
          _cancelAndRestartTimer();
        },
        child: SizedBox(
          child: Stack(
            children: <Widget>[
              // 中间按钮
              Visibility(
                visible: !_isBuffering,
                child: Align(
                  alignment: Alignment.center,
                  child: _buildCenterBtns(context),
                ),
              ),
              Visibility(
                visible: _isBuffering,
                child: const Align(
                  alignment: Alignment.center,
                  child: AvPlayerLoading(),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSpeeds() {
    return _showSpeed
        ? Positioned.fill(
            child: Container(
            color: const Color.fromRGBO(0, 0, 0, 0.5),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: _speeds.map((v) {
                return Container(
                  alignment: Alignment.center,
                  color: COLOR.hexColor(_speed == v ? '#B93FFF' : '#262626'),
                  height: 30,
                  width: 50,
                  margin: const EdgeInsets.symmetric(horizontal: 8),
                  child: Text('X$v'),
                ).onTap(() async {
                  await controller(context).player.setRate(double.parse(v));
                  EasyToast.show('X$v');
                  setState(() {
                    _speed = v;
                    _showSpeed = false;
                  });
                });
              }).toList(),
            ),
          ).onTap(() {
            setState(() {
              _showSpeed = false;
            });
          }))
        : const SizedBox.shrink();
  }

  @override
  Widget build(BuildContext context) {
    Rect rect = isFullscreen(context)
        ? Rect.fromLTWH(
            0,
            0,
            Get.width,
            Get.height,
          )
        : Rect.fromLTRB(
            max(0.0, widget.texturePos?.left ?? 0),
            max(0.0, widget.texturePos?.top ?? 0),
            min(widget.viewSize?.width ?? 0, widget.texturePos?.right ?? 0),
            min(widget.viewSize?.height ?? 0, widget.texturePos?.bottom ?? 0),
          );

    return VideoControlsThemeDataInjector(
      child: WillPopScope(
        child: SizedBox.fromSize(
          size: Size(rect.width, rect.height),
          child: GestureDetector(
            onTap: _cancelAndRestartTimer,
            // behavior: HitTestBehavior.opaque,
            // onHorizontalDragStart: _onHorizontalDragStart,
            // onHorizontalDragUpdate: _onHorizontalDragUpdate,
            // onHorizontalDragEnd: _onHorizontalDragEnd,
            child: AbsorbPointer(
              absorbing: _hideStuff,
              child: Stack(
                children: [
                  Column(
                    children: <Widget>[
                      // 播放器顶部控制器
                      _buildTopBar(context),
                      //中间
                      _buildCenterBox(context),
                      // 播放器底部控制器
                      _buildBottomBar(context),
                      //底部间隙
                      isFullscreen(context) ||
                              (widget.viewSize?.height ?? 0) < Get.height
                          ? const SizedBox.shrink()
                          : SizedBox(
                              height:
                                  MediaQuery.of(context).padding.bottom + 15),
                    ],
                  ),
                  _buildSpeeds()
                ],
              ),
            ),
          ),
        ),
        onWillPop: () async {
          if (!isFullscreen(context)) controller(context).player.stop();
          return true;
        },
      ),
    );
  }
}
